﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.ComponentModel;
using System.Collections.Specialized;


namespace purchases.Controls
{
    public class contractDetailGrid : common.controls.baseDataGridView 
    {
        public contractDetailGrid()
        {
            this.myAutoFitColumn = ColumnNames.itemName.ToString();
            this.AutoArrange();
            this.myOnFind += new OnCellEvent(FindData);
            this.myOnCellValueChanged += new OnCellEvent(ValueChanged);
        }

        public enum ColumnNames
        {
            itemCode, itemName, itemUnit, qty, price, fPrice, amount, currency, fAmount, tax1Percent, tax1Amt, notes
        };

        private void UpdateItemList(string itemCode)
        {
            if (itemCode == null)
            {
                for (int idx = 0; idx < this.Rows.Count; idx++)
                {
                    if (this.Rows[idx].Cells[ColumnNames.itemCode.ToString()].Value == null) continue;
                    DataAccess.DataCache.FindITEM(this.Rows[idx].Cells[ColumnNames.itemCode.ToString()].Value.ToString());
                }
            }
            else DataAccess.DataCache.FindITEM(itemCode);
        }
        public override void Init(BindingSource dataSource)
        {
            data.applicationDS.ContractDetailDataTable contractDetailTbl = new data.applicationDS.ContractDetailDataTable();
            base.Init(dataSource);
            DataGridViewCellStyle qtyCellType = new DataGridViewCellStyle();
            DataGridViewCellStyle amountCellType = new DataGridViewCellStyle();
            DataGridViewCellStyle fAmountCellType = new DataGridViewCellStyle();
            DataGridViewCellStyle percentCellType = new DataGridViewCellStyle();

            qtyCellType.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight;
            string precisionQtyStr = common.SysLibs.GetPrecisionFromMask(CommonTypes.Settings.sysMaskQty).ToString();
            qtyCellType.Format = "N" + precisionQtyStr; 
            qtyCellType.NullValue = null;
            
            amountCellType.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight;
            string precisionLocalAmtStr = common.SysLibs.GetPrecisionFromMask(CommonTypes.Settings.sysMaskLocalAmt).ToString();
            amountCellType.Format = "N" + precisionLocalAmtStr;  
            amountCellType.NullValue = null;

            fAmountCellType.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight;
            string precisionForeignAmtStr = common.SysLibs.GetPrecisionFromMask(CommonTypes.Settings.sysMaskForeignAmt).ToString();
            fAmountCellType.Format = "N" + precisionForeignAmtStr;
            fAmountCellType.NullValue = null;

            percentCellType.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight;
            string precisionPercentAmtStr = common.SysLibs.GetPrecisionFromMask(CommonTypes.Settings.sysMaskPercentTax).ToString();
            percentCellType.Format = "N" + precisionPercentAmtStr;  
            percentCellType.NullValue = null;

            // 
            // itemCode
            // 
            common.controls.DataGridViewTextBoxColumnExt itemCode = new common.controls.DataGridViewTextBoxColumnExt();
            itemCode.DataPropertyName = contractDetailTbl.itemCodeColumn.ColumnName;;
            itemCode.HeaderText = " Mã.hàng";
            itemCode.Name = ColumnNames.itemCode.ToString();
            itemCode.Width = 90;
            itemCode.Uppercase = true;

            // 
            // itemName
            // 
            DataGridViewComboBoxColumn itemName = new DataGridViewComboBoxColumn();
            BindingSource itemSource = new BindingSource();
            itemSource.DataSource = DataAccess.DataCache.myMasterDS.Item;

            itemName.DataSource = itemSource;
            itemName.DataPropertyName = DataAccess.DataCache.myMasterDS.Item.itemCodeColumn.ColumnName;
            itemName.DisplayMember = DataAccess.DataCache.myMasterDS.Item.nameColumn.ColumnName;
            itemName.ValueMember = DataAccess.DataCache.myMasterDS.Item.itemCodeColumn.ColumnName;
            itemName.HeaderText = "Hàng.hoá";
            itemName.Name = ColumnNames.itemName.ToString();
            itemName.ReadOnly = true;
            itemName.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
            itemName.Width = 170;
            itemName.DefaultCellStyle.BackColor = CommonTypes.Settings.sysColorDisableBG;
            itemName.DefaultCellStyle.ForeColor = CommonTypes.Settings.sysColorDisableFG;

            // 
            // unit
            // 
            DataGridViewComboBoxColumn unit = new DataGridViewComboBoxColumn();
            unit.DataSource = itemSource;
            unit.DataPropertyName = DataAccess.DataCache.myMasterDS.Item.itemCodeColumn.ColumnName;
            unit.DisplayMember = DataAccess.DataCache.myMasterDS.Item.unitColumn.ColumnName;
            unit.ValueMember = DataAccess.DataCache.myMasterDS.Item.itemCodeColumn.ColumnName;
            unit.HeaderText = "ĐVT";
            unit.Name = ColumnNames.itemUnit.ToString();
            unit.ReadOnly = true;
            
            unit.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
            unit.DefaultCellStyle.BackColor = CommonTypes.Settings.sysColorDisableBG;
            unit.DefaultCellStyle.ForeColor = CommonTypes.Settings.sysColorDisableFG;
            unit.Width = 60;
            // 
            // Qty
            // 
            DataGridViewTextBoxColumn qty = new DataGridViewTextBoxColumn();
            qty.DataPropertyName = contractDetailTbl.qtyColumn.ColumnName;
            qty.HeaderText = "Lượng";
            qty.Name = ColumnNames.qty.ToString();
            qty.DefaultCellStyle = qtyCellType;
            qty.Width = 80;

            // 
            // price
            // 
            DataGridViewTextBoxColumn price = new DataGridViewTextBoxColumn();
            price.DataPropertyName = contractDetailTbl.priceColumn.ColumnName;
            price.HeaderText = "Giá";
            price.Name = ColumnNames.price.ToString();
            price.DefaultCellStyle = amountCellType;
            price.Width = 80;

            // 
            // amount
            // 
            DataGridViewTextBoxColumn amount = new DataGridViewTextBoxColumn();
            amount.DataPropertyName = contractDetailTbl.amountColumn.ColumnName;
            amount.HeaderText = "Số tiền";
            amount.Name = ColumnNames.amount.ToString();
            amount.DefaultCellStyle = amountCellType ;
            amount.Width = 90;

            // 
            // fPrice
            // 
            DataGridViewTextBoxColumn fPrice = new DataGridViewTextBoxColumn();
            fPrice.DataPropertyName = contractDetailTbl.fPriceColumn.ColumnName;
            fPrice.HeaderText = "Giá";
            fPrice.Name = ColumnNames.fPrice.ToString();
            fPrice.DefaultCellStyle = fAmountCellType;
            fPrice.Width = 70;
            fPrice.Visible = false;

            // 
            // fAmount
            // 
            DataGridViewTextBoxColumn fAmount = new DataGridViewTextBoxColumn();
            fAmount.DataPropertyName = contractDetailTbl.fAmountColumn.ColumnName;
            fAmount.HeaderText = "Số tiền";
            fAmount.Name = ColumnNames.fAmount.ToString();
            fAmount.DefaultCellStyle = fAmountCellType;
            fAmount.Width = 80;
            fAmount.Visible = false;

            // 
            // tax1Perc
            // 
            DataGridViewTextBoxColumn tax1Perc = new DataGridViewTextBoxColumn();
            tax1Perc.DataPropertyName = contractDetailTbl.tax1PercColumn.ColumnName;
            tax1Perc.HeaderText = "%";
            tax1Perc.Name = ColumnNames.tax1Percent.ToString();
            tax1Perc.DefaultCellStyle = percentCellType;
            tax1Perc.Width = 30;
            tax1Perc.Visible = true;

            // 
            // tax1Amt
            // 
            DataGridViewTextBoxColumn tax1Amt = new DataGridViewTextBoxColumn();
            tax1Amt.DataPropertyName = contractDetailTbl.tax1Column.ColumnName;
            tax1Amt.HeaderText = "Thuế";
            tax1Amt.Name = ColumnNames.tax1Amt.ToString();
            tax1Amt.DefaultCellStyle = amountCellType;
            tax1Amt.Width = 90;
            tax1Amt.Visible = true;

            // 
            // currency
            // 
            DataGridViewTextBoxColumn currency = new DataGridViewTextBoxColumn();
            currency.DataPropertyName = contractDetailTbl.currencyColumn.ColumnName;
            currency.HeaderText = "$";
            currency.Name = ColumnNames.currency.ToString();
            currency.Width = 40;
            currency.Visible = false;
            // 
            // Notes
            // 
            DataGridViewTextBoxColumn notes = new DataGridViewTextBoxColumn();
            notes.DataPropertyName = contractDetailTbl.notesColumn.ColumnName;;
            notes.HeaderText = "  Ghi chú";
            notes.Name = ColumnNames.notes.ToString();
            notes.Width = 100;
            notes.Visible =true;

            // 
            // myDetailGrid
            // 
            this.DataSource = dataSource;

            this.AutoGenerateColumns = false;
            this.Columns.Clear();
            this.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
                    itemCode,itemName,unit,qty,price,fPrice,amount,fAmount,tax1Perc,tax1Amt,currency,notes});
        }

        protected override void OnDefaultValuesNeeded(DataGridViewRowEventArgs e)
        {
            base.OnDefaultValuesNeeded(e);
            if (e == null) return;
            decimal saveTaxPercent1 = 0;
            if (this.CurrentRow != null)
            {
                decimal.TryParse(this.CurrentRow.Cells[ColumnNames.tax1Percent.ToString()].Value.ToString(), out saveTaxPercent1);
            }
            if (myDataSource.Current != null)
                DataAccess.DataLibs.InitData((data.applicationDS.ContractDetailRow)((DataRowView)myDataSource.Current).Row);
            e.Row.Cells[ColumnNames.tax1Percent.ToString()].Value = saveTaxPercent1;
        }

        public override void Import(string fromFile)
        {
            StringCollection sheetName = common.import.GetExcelSheetName(fromFile);
            DataTable tbl = new DataTable();
            if (!common.import.ImportFromExcel(fromFile, sheetName[0], tbl)) return;
            string itemCode = "";
            decimal qty = 0, price = 0, taxPerc = 0;

            data.applicationDS.ContractDetailDataTable detailTbl = (data.applicationDS.ContractDetailDataTable)this.myDataSource.DataSource;
            data.applicationDS.ContractDetailRow detailRow;
            for (int idx = 0; idx < tbl.Rows.Count; idx++)
            {
                itemCode = tbl.Rows[idx][0].ToString().Trim();
                if (itemCode == "") continue;
                if (!decimal.TryParse(tbl.Rows[idx][1].ToString(), out qty)) continue;
                if (!decimal.TryParse(tbl.Rows[idx][2].ToString(), out price)) continue;
                if (!decimal.TryParse(tbl.Rows[idx][3].ToString(), out taxPerc)) continue;

                detailRow = detailTbl.NewContractDetailRow();
                DataAccess.DataLibs.InitData(detailRow);
                detailRow.itemCode = itemCode;
                if (DataAccess.DataCache.FindITEM(itemCode) == null)
                {
                    DataAccess.DataLibs.AddItem(itemCode, CommonTypes.Settings.sysNewData, "", "", "");
                    DataAccess.DataCache.FindITEM(itemCode);
                }

                detailRow.qty = qty;
                detailRow.price = price;
                detailRow.tax1Perc = taxPerc;

                if (this.Columns[ColumnNames.amount.ToString()].Visible)
                    detailRow.amount = detailRow.qty * detailRow.price;
                if (this.Columns[ColumnNames.tax1Amt.ToString()].Visible)
                {
                    int precisionLocalAmt = common.SysLibs.GetPrecisionFromMask(CommonTypes.Settings.sysMaskLocalAmt);
                    detailRow.tax1 = Math.Round((detailRow.amount * detailRow.tax1Perc) / 100, precisionLocalAmt);
                }
                if (this.Columns[ColumnNames.notes.ToString()].Visible && tbl.Columns.Count >= 5)
                    detailRow.notes = tbl.Rows[idx][4].ToString();
                detailTbl.AddContractDetailRow(detailRow);
            }
        }

        public override void Refresh()
        {
            if (IsOnProcessing) return;
            try
            {
                IsOnProcessing = true;
                UpdateItemList(null);
                IsOnProcessing = false;
                base.Refresh();
            }
            catch (Exception er)
            {
                IsOnProcessing = false;
                ErrorHandler(this, er);
            }
        }

        private void FindData(object sender, common.controls.GridEventArgs args)
        {
            string findCode = this.Rows[args.RowIndex].Cells[args.ColumnIndex].EditedFormattedValue.ToString(); ;
            if (this.CurrentCell == null) return;
            //Code
            if (this.Columns[args.ColumnIndex].Name.Trim() == ColumnNames.itemCode.ToString())
            {
                application.dataFind.myItemFind.Find(findCode, true);
                data.masterDS.ItemRow itemRow = application.dataFind.myItemFind.selectedDataRow;
                if (itemRow != null)
                {
                    this.Rows[args.RowIndex].Cells[args.ColumnIndex].Value = itemRow.itemCode;
                    UpdateItemList(itemRow.itemCode);
                    this.myDataSource.ResetBindings(false);
                    this.myDataSource.EndEdit(); 
                }
                else this.Rows[args.RowIndex].Cells[args.ColumnIndex].Value = DBNull.Value;
            }
        }
        private void ValueChanged(object sender, common.controls.GridEventArgs e)
        {
            //if (this.CurrentRow == null || this.CurrentRow.DataBoundItem==null) return;
            if (this.CurrentCell == null || !this.IsValidCell(e.RowIndex, e.ColumnIndex)) return;
            if (this.Columns[e.ColumnIndex].Name == ColumnNames.itemCode.ToString())
            {
                string itemCode = this.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                if (common.StringLibs.IsNullOrEmpty(itemCode) == false)
                {
                    bool HaveMarker = common.SysLibs.HaveFindMarker(ref itemCode);
                    if (HaveMarker == false)
                    {
                        string code = application.AppLibs.GetItemCodeFromCodeId(itemCode);
                        if (code != null)
                        {
                            itemCode = code;
                            this.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = itemCode;
                        }
                    }
                    data.masterDS.ItemRow itemRow = DataAccess.DataCache.FindITEM(itemCode);
                    if (itemRow == null) FindData(this, e);
                }
            }

            data.applicationDS.ContractDetailRow detailRow = null;
            int precisionLocalAmt = common.SysLibs.GetPrecisionFromMask(CommonTypes.Settings.sysMaskLocalAmt);
            if (this.Columns[e.ColumnIndex].Name == ColumnNames.price.ToString() ||
                this.Columns[e.ColumnIndex].Name == ColumnNames.qty.ToString())
            {
                detailRow = (data.applicationDS.ContractDetailRow)((DataRowView)this.CurrentRow.DataBoundItem).Row;
                if (this.Columns[ColumnNames.amount.ToString()].Visible)
                    detailRow.amount = Math.Round(detailRow.qty * detailRow.price, precisionLocalAmt);
                if (this.Columns[ColumnNames.tax1Amt.ToString()].Visible)
                    detailRow.tax1 = Math.Round((detailRow.amount * detailRow.tax1Perc) / 100, precisionLocalAmt);
            }
            if (this.Columns[e.ColumnIndex].Name == ColumnNames.tax1Percent.ToString())
            {
                detailRow = (data.applicationDS.ContractDetailRow)((DataRowView)this.CurrentRow.DataBoundItem).Row;
                if (this.Columns[ColumnNames.tax1Amt.ToString()].Visible)
                    detailRow.tax1 = Math.Round((detailRow.amount * detailRow.tax1Perc) / 100, precisionLocalAmt);
            }
        }
    }
}
